<template>
  <div>
    <div h-100rpx>
      <uNavbar>
        <nut-input @clear="search()" show-clear-icon :clearable="true" v-model="goodsName" @confirm="search"
                   :input-style="searchStyle" :custom-style="searchStyle" placeholder="请输入搜索商品">
          <template #left>
            <div pl-18rpx flex flex-a-c> <nut-icon name="search" /> </div>
          </template>
        </nut-input>
      </uNavbar>
    </div>
    <div p-16rpx>
      <scroll-view :scroll-top="scrollTop" @scrolltolower="reachBottom" :lower-threshold="100" scroll-with-animation
                   :style="{ height: popupHeight('height'), marginTop: popupHeight('marginTop') }" :scroll-y="true">
        <div v-if="isShow">
          <div v-if="goodsList.records && goodsList.records.length">
            <div :key="index" v-for="(item, index) in goodsList.records" mb-20rpx>
              <oneRowDistribution :res="item" @handleLink="handleLink"></oneRowDistribution>
            </div>
          </div>
          <empty v-else />
        </div>
      </scroll-view>
    </div>
    <!-- 分销商品海报弹框 -->
   <nut-popup :closeable="true" position="bottom" round :custom-style="{ height: '1120rpx', width: '100vw', overflow: 'hidden' }" v-model:visible="sharingShow">
      <div class="sharingContent" flex flex-col items-center justify-between text-28rpx box-border pt-30rpx>
        <div v-if="placardGoods.commission">分享后预计可赚<span class="text-main-color">￥{{goodsFormatPrice(placardGoods.commission)[0]}}.{{goodsFormatPrice(placardGoods.commission)[1]}}</span></div>
        <div mt-6rpx text-neutral-500 text-26rpx>佣金可在“分销员中心”里查看</div>
        <div mt-18rpx text-neutral-400 text-26rpx>长按海报保存到相册</div>
        <div class="canvas-box" my-20rpx border-slate-100 border-1 border-solid bg-gray-50 v-if="disExample && disExample.memberInfo">
          <image :src="posterPath" mode="widthFix" style="width: 580rpx; height: 840rpx" show-menu-by-longpress></image>
          <l-painter css="width: 580rpx; height: 840rpx;background-color: #f6f7fb;" pathType="url" ref="poster" hidden isCanvasToTempFilePath @success="posterPath = $event">
            <l-painter-image :src="disExample.memberInfo.face"
                             css="width: 84rpx; height: 84rpx; background: #ffffff; object-fit: cover; margin-left: 40rpx; margin-top: 30rpx; box-sizing: border-box; border-radius: 50%;"/>
            <l-painter-view css="margin-top: 30rpx; padding-left: 20rpx; display: inline-block">
              <l-painter-text :text="disExample.memberInfo.nickName" css="display: block; padding-bottom: 10rpx; color: #333333; font-size: 32rpx; fontWeight: bold"/>
              <l-painter-text :text="disExample.memberInfo.desc" css="color: #333333; font-size: 24rpx"/>
            </l-painter-view>
            <l-painter-view css="width: 540rpx; margin: 20rpx 20rpx; padding: 20rpx; box-sizing: border-box; background: #ffffff; border-radius: 4rpx; box-shadow: 0 0 20rpx rgba(0,0,0,.1);position: relative;">
            	<l-painter-image :src="disExample.bottom.img"  css="object-fit: cover; object-position: 50% 50%; width: 500rpx; height: 500rpx;"/>
              <l-painter-view css="height: 120rpx; margin-top: 20rpx; color: #FF0000; font-size: 28rpx; line-height: 1em;">
            		<l-painter-text :text="disExample.bottom.price" css="vertical-align: bottom; font-size: 40rpx; display: block;"/>
            		<l-painter-text :text="disExample.bottom.title" css="margin-top: 10rpx;padding-left: 10rpx;color: #666666;line-height: 1.3em;width: 350rpx;height: 70rpx;overflow: hidden;"/>
            	</l-painter-view>
              <l-painter-image :src="disExample.bottom.code"  css="width: 128rpx; height: 128rpx; position: absolute; right: 20rpx; bottom: 20rpx;"/>
              <!-- <l-painter-qrcode css="width: 128rpx; height: 128rpx; position: absolute; right: 20rpx; bottom: 20rpx;" :text="disExample.bottom.code"></l-painter-qrcode> -->
            </l-painter-view>
          </l-painter>
        </div>
        <!-- <div w-full px-40rpx box-border><nut-button block type="warning" size="small" @click="copyLink()">复制链接</nut-button></div> -->
        <lime-painter style="position: fixed; left: 200%" />
      </div>
    </nut-popup>
  </div>
</template>

<script setup lang="ts">
import empty from '@/components/empty/index.vue';
import oneRowDistribution from '@/components/goods-list/1row-distribution.vue';
import { back, searchStyle } from '@/components/goods-list/common';
import { onLoad } from '@dcloudio/uni-app';
import { distributionGoods, getMpCode } from "@/api/goods";
import { getQrcode } from '@/api/common';
import configs from '@/config/config';
import storage from '@/utils/storage';
import { unitPrice, goodsFormatPrice } from '@/utils/filters';
import uNavbar from '@/components/navbar/index.vue';
const scrollTop = ref<number>(0) //scroll 为0 回到顶部
const isShow = ref<boolean>(false) //是否展示内容
const routerVal = ref<any>({})
const searchForm = ref<any>({
  pageNumber: 1,
  pageSize: 10,
  sort: "createTime",
  order: "desc",
  // checked: true
  goodsName: ''
})
const goodsList = ref<any>({
  records: [],
  total: 0
})
const goodsName = ref<string>('')
// 海报部分
const sharingShow = ref<Boolean>(false);  // 展示分享海报
const placardGoods = ref<any>({});	// 当前分销商品
const sharingLink = ref<string>(""); // 分享链接
// 分销分享 实例
const disExample = ref<any>({
  memberInfo: {
    face: storage.getUserInfo().face || "/static/default.png", //头像
    nickName: storage.getUserInfo().nickName || "",
    mobile: storage.getUserInfo().mobile || "",
    desc: "为你挑选了一个好物"
  },
  // 分销分享
  bottom: {
    img: "",
    code: "",
    price: 0,
    title: ""
  },
})
const poster = ref<any>('');  // 海报ref
const posterPath = ref<string>(''); // 海报临时路径
// 分享二维码生成
async function handleLink(goods: any) {
  try {
    placardGoods.value = goods;
    //微信小程序 二维码逻辑
    // #ifdef MP-WEIXIN
    // #endif
    // 非小程序逻辑
    // #ifndef MP-WEIXIN
    // #endif
    // 获取小程序二维码
    uni.showLoading({ title: "海报生成中...", mask: true });
    const accountInfo = uni.getAccountInfoSync();
    const envVersion = accountInfo.miniProgram.envVersion;
    
    // 获取小程序二维码的参数
    const qrCodeParams = {
      page: "pages/goods/product/detail",
      scene: `${goods.skuId},${goods.goodsId},${routerVal.value.id}`,
      check_path: envVersion === 'release' ? true : false,
      envVersion: envVersion,
      width: 280
    }
    const qrCodeUrl:string = await getQrcode(qrCodeParams);
    // if (res.code === 200) {
    //   disExample.value.bottom.code = res.data;
    // }
    // sharingLink.value = configs.shareLink + "/pages/goods/product/detail?skuId=" + goods.skuId + "&goodsId=" + goods.goodsId + "&distributionId=" + routerVal.value.id;
    disExample.value.bottom = {
      code: qrCodeUrl,
      price: unitPrice(goods.price,"￥"),
      img: `${goods.thumbnail}`,
      title: `${goods.goodsName}`,
    }
    uni.hideLoading()
    sharingShow.value = true;
  } catch (error) {
    uni.hideLoading()
  }
  
}
function h5Copy(content: string) {
  if (!document.queryCommandSupported('copy')) {
    // 不支持
    return false
  }
  let textarea = document.createElement("textarea")
  textarea.value = content
  textarea.readOnly = true
  document.body.appendChild(textarea)
  textarea.select() // 选择对象
  textarea.setSelectionRange(0, content.length) //核心
  let result = document.execCommand("copy") // 执行浏览器复制命令
  textarea.remove()
  uni.showToast({
    title: "复制成功!",
    icon: "none"
  })
  return result
}
// 复制链接
function copyLink() {
  // #ifdef H5
  h5Copy(sharingLink.value);
  // #endif

  // #ifndef H5
  uni.setClipboardData({
    data: sharingLink.value,
    success: () => {
      uni.showToast({
        title: "复制成功!",
        duration: 3000,
        icon: "none",
      });
    },
    fail:(error)=> {
      console.log('失败',error);
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  });
  // #endif
}

function saveImage() {
  poster.value.canvasToTempFilePathSync({
    fileType: "jpg",
    // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
    pathType: 'url',
    quality: 1,
    success: (res: any) => {
      console.log(res.tempFilePath);
      // 非H5 保存到相册
      // H5 提示用户长按图另存
      uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
              console.log('save success');
          }
      });
    },
  });
}

// 兼容popupHeight
const popupHeight = (type: 'height' | 'marginTop') => {
// #ifndef H5
return type === 'marginTop' ? '90rpx' : 'calc(100vh - 280rpx)'
// #endif
}

// 触底加载
function reachBottom() {
  if (searchForm.value.pageSize * searchForm.value.pageNumber < goodsList.value.total) {
    searchForm.value.pageNumber++
    fetch()
  }
}

function init() {
  isShow.value = false
  goodsList.value.records = []
  searchForm.value.pageSize = 10
  searchForm.value.pageNumber = 1
  fetch()
}

async function fetch() {
  const res = await distributionGoods(searchForm.value)
  isShow.value = true
  if (res.data.success) {
    goodsList.value.records.push(...res.data.result.records)
    goodsList.value.total = res.data.result.total
    console.log('初始化', goodsList.value.records, goodsList.value.total);
  }
}

function search() {
  goodsList.value.records = []
  searchForm.value.goodsName = goodsName.value
  init();
}

onLoad((options: any) => {
  routerVal.value = options
})

onMounted(() => {
  init()
})
</script>


<style scoped lang="scss">
page {
  background: #fff;
}
</style>

